package com.kayang.common.aop;

import com.kayang.common.db.Database;
import com.kayang.common.db.DatabaseFactory;
import com.kayang.common.exception.SPserviceException;
import com.kayang.common.languages.MSGAlarm;
import com.kayang.nadapt.util.JsonConvert;
import com.kayang.nadapt.util.LogHelper;
import com.kayang.nadapt.util.StringUtil;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.Signature;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.springframework.stereotype.Component;

@Aspect
@Component
public class SPServiceMethodAspect {

    @Around("@annotation(com.kayang.common.aop.SPEnable)")
    public Object logExecutionTime(ProceedingJoinPoint joinPoint) throws Throwable {
        Signature signature = joinPoint.getSignature();
        String methodName = signature.getName();
        String clsName = signature.getDeclaringTypeName();
        Object[] args = joinPoint.getArgs();
        BaseContext context = null;
        Object[] argNames = new Object[args.length];
        int i = 0;
        for (Object arg : args) {
            if(arg instanceof BaseContext){
                context = (BaseContext) arg;
            }
            argNames[i] = arg.getClass().getSimpleName();
            i++;
        }

        LogHelper.info(StringUtil.format("SPEnable执行记录,  Class:{0}, Method:{1}, Args:[{2}], Args-Body:{3}", clsName, methodName, JsonConvert.serializeObject(argNames), JsonConvert.serializeObject(args)));

        IService service = (IService) joinPoint.getTarget();
        if(context != null){
            try{
                execSp(service.getBeforeSp(), context);
            }catch (Exception e){
                LogHelper.error("SPEnable执行记录, Before Exec Failed" , e);
            }

        }

        // 执行目标方法
        Object proceed = joinPoint.proceed();

        LogHelper.info("SPEnable执行记录, 业务方法" + methodName + "执行OK, 返回: " + JsonConvert.serializeObject(proceed));

        if(context != null){
            try{
                execSp(service.getAfterSp(), context);
            }catch (Exception e){
                LogHelper.error("SPEnable执行记录, After Exec Failed" , e);
            }

        }

        return proceed;
    }

    private void execSp(String spname, BaseContext context){
        Database db = DatabaseFactory.getDatabase();
        Object o = db.execProc(spname, JsonConvert.serializeObject(context));
        if(StringUtil.isNullOrEmpty(o)){
            MSGAlarm msgAlarm = MSGAlarm.create(o, db, 2052);
            if(msgAlarm.getHasAlarm()){
                throw new SPserviceException(msgAlarm);
            }
        }
    }
}
